//
//  YMSearchResultView.swift
//  YMSwiftUI
//
//  Created by anscen on 2022/4/2.
//

import SwiftUI
import SDWebImageSwiftUI

struct YMSearchResultView: View {
    @State var nickName :String
    @State private var listAdap :[GridItem] =  [GridItem(.adaptive(minimum: list_width, maximum: list_width + 10), spacing: 0, alignment: .center)]
    @State private var listData :[YMBook] = []
    @State private var refreshData = BaseRefreshData()
    func loadRefreshAction(){
        self.loadData(1)
    }
    func loadMoreAction(){
        self.loadData(refreshData.page)
    }
    var body: some View {
        GeometryReader(alignment: .center) { root in
            VStack(alignment: .center, spacing: 10) {
                YMSearchTextView(textName: $nickName)
                if listData.count == 0{
                    BaseRefreshView(refreshing: $refreshData.refreshHeader).frame(width: root.size.width, height: root.size.height, alignment: .center)
                }
                ScrollView(.vertical, showsIndicators: false){
                    RefreshHeader(refreshing: $refreshData.refreshHeader) {
                        self.loadRefreshAction()
                    } label: { progess in
                        BaseRefreshHeaderView(refreshing: refreshData.refreshHeader)
                    }
                    LazyVGrid(columns: listAdap, spacing: 0){
                        ForEach(listData, id: \.self){
                            item in
                            YMListCell(book: item,width: root.size.width)
                        }
                    }
                    RefreshFooter(refreshing: $refreshData.refreshFooter, action: loadMoreAction) {
                        BaseRefreshFooterView(noMoreData: refreshData.noMoreData,refreshing: refreshData.refreshFooter)
                    }.preload(offset: 50).noMore(refreshData.noMoreData)
                }.enableRefresh()
            }.onAppear {
                self.refreshData.refreshHeader = true
                self.loadRefreshAction()
            }.onDisappear {

            }.navigationBarHidden(true)
        }
    }
    func loadData(_ page :Int){
        ApiMoya.request(target: .search(nickName, page)) { json in
            debugPrint(json)
            if page == 1{
                self.listData.removeAll()
            }
            guard let list = [YMBook].deserialize(from: json["books"].rawString()) else { return }
            if let data = list as? [YMBook]{
                refreshData.page = refreshData.page + 1
                self.listData.append(contentsOf: data)
            }
            refreshData.endRefresh(list.count == 0)
        } failure: { error in
            refreshData.endFailure(error)
        }
    }
}
